<?php

class defaultActions extends sfActions
{
    /**
     * For Custom Channel URL, see http://developers.facebook.com/docs/reference/javascript/FB.init/
     *
     * TODO: use localized all.js?
     */
    public function executeChannel($request)
    {
        // Page expires in one year
        header('Expires: '.gmstrftime('%a, %d %b %Y %H:%M:%S GMT', time() + 365*86440));
        $url = 'http'.($request->isSecure() ? 's' : '').'://connect.facebook.net/en_US/all.js';
        return $this->renderText('<script src="'.$url.'"></script>');
    }


    /**
     * Error page for page not found (404) error
     *
     */
    public function executeError404()
    {
    }


    /**
     * Warning page for restricted area - requires login
     *
     */
    public function executeLogin($request)
    {
        if ($request->isXmlHttpRequest()) {
            // Ajax request in an iframe or on the tabbed profile
            return $this->ajaxError('login');
        } elseif ($signed_request = App::getFacebookClient()->getSignedRequest()) {
            // IFrame inital POST
            $url = App::getFacebookClient()->getLoginUrl(array(
                    'redirect_uri'       => UrlFunctions::genFbUrl($request->getParameterHolder()->getAll(), true),
                    ));

            $needed_credentials = $this->getContext()->getActionStack()->getFirstEntry()->getActionInstance()->getCredential();

            if ($needed_credentials === 'page_admin' || $needed_credentials === 'super_admin')
                $url .= '&scope=manage_pages';

            vtnsLog::debug('{LoginAction} redirecting to %s', $url);
            return $this->renderText("<script type=\"text/javascript\">\ntop.location.href = \"$url\";\n</script>");
        } else {
            // IFrame without FB POST
            return $this->executeSecure($request);
        }
    }


    /**
     * Warning page for restricted area - requires credentials
     *
     */
    public function executeSecure($request)
    {
        if ($request->isXmlHttpRequest())
            // Ajax request in an iframe or on the tabbed profile
            return $this->ajaxError('secure');
        elseif ($request->isMethod(sfRequest::POST))
            // IFrame inital POST: go to @homepage to avoid a redirection loop
            // IFrame POST request: do not pass parameters to GET redirection
            return $this->reloadIFrame('@homepage');
        else
            // IFrame standard request
            return $this->reloadIFrame($request->getParameterHolder()->getAll());
    }


    /**
     * Reload current page, but ensure that it is loaded over SSL
     */
    public function executeSSL($request)
    {
        $parameters = $request->getParameterHolder()->getAll();

        // signed_request is provided by Facebook
        unset($parameters['signed_request']);

        // Reload iframe and force SSL
        return $this->reloadIFrame($parameters, true);
    }


    private function ajaxError($error)
    {
        // Ensure handling by generic Ajax error handler
        $this->getContext()->getLogger()->debug("{SecureAction} Ajax request error: ".$error);

        $response = sfContext::getInstance()->getResponse();
        $response->setStatusCode(403);

        return $this->renderText(json_encode(array(
                    'error' => $error,
                    )));
    }


    private function reloadIFrame($parameters, $ssl = null)
    {
        // TODO: handle secondary applications (tab name change)
        $url = UrlFunctions::genFbUrl($parameters, true, null, $ssl);
        $this->getContext()->getLogger()->debug("{SecureAction} IFrame redirection to: ".$url);
        return $this->renderText("<script type=\"text/javascript\">\ntop.location.href = \"$url\";\n</script>");
    }
}

